﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sl.Support.McuBytes;

namespace ChholCmdPort {
	public class Pkg{
		public Cc9d.Pkg cc9d_pkg;
		public ushort Remote_addr {
			get {
				return BitConverter.ToUInt16(cc9d_pkg.Buf, 2); 
			}
			set {
				cc9d_pkg.Buf[2] = value.ByteLow();
				cc9d_pkg.Buf[3] = value.ByteHigh();
			}
		}
		public byte From_port { get => cc9d_pkg.Buf[0]; set => cc9d_pkg.Buf[0] = value; }
		public byte To_port { get => cc9d_pkg.Buf[1]; set => cc9d_pkg.Buf[1] = value; }
		public byte this[int i] { get => cc9d_pkg.Buf[i + 4]; set => cc9d_pkg.Buf[i + 4] = value; }
		public int Data_len { get => cc9d_pkg.Len - 5; set => cc9d_pkg.Len = 5 + value; }

		public byte[] Data { 
			get => cc9d_pkg.Buf.Skip(4).Take(Data_len).ToArray();
			set {
				for (int i = 0; i < value.Length; i++) {
					this[i] = value[i];
				}
				Data_len = value.Length;
			}
		}


		public void loadData(params byte[] data) {
			for (int i = 0; i < data.Length; i++) {
				this[i] = data[i];
			}
			Data_len = data.Length;
		}
		public override string ToString() {
			if (cc9d_pkg.Is_send) {
				return $"{From_port}->{Remote_addr:X4}.{To_port} SEND: {cc9d_pkg.Buf.toHexStr(4, Data_len)}";
			} else {
				return $"{Remote_addr:X4}.{From_port}->{To_port} RECV: {cc9d_pkg.Buf.toHexStr(4, Data_len)}";
			}
		}
		public Pkg(){
			cc9d_pkg = new Cc9d.Pkg();
		}
		public Pkg(Cc9d.Pkg pkg) {
			cc9d_pkg = pkg;
		}


	}
}
